<template>
	<Page>
		<Topbar hideMenu />
		<Content>
			<Panel>
				<view class="left">
					<Info hideCuttingPlan :data="workInfo" backUrl="/pages/workbench/inspect/index" />
				</view>
				<FormWrap header title="自检报废" height="68vh">
					<u--form :labelPosition="labelPosition" labelAlign="left" :model="model" :rules="rules" ref="uForm"
						labelWidth="12rem" :labelStyle="{'margin-bottom' : labelPosition === 'top' ? '2rem' : '0'}"
						style="
                        margin-top: 2rem; padding: 0 5rem;">
						<u-form-item label="处理类型" prop="checkType">
							<u-radio-group v-model="model.checkType" placement="row" @change="changeCheckType">
								<u-radio v-for="(item, index) in checkTypes" :key="index" :label="item.label"
									:name="item.label">
								</u-radio>
							</u-radio-group>
						</u-form-item>
						<u-form-item label="不良原因" prop="outReason" class="label-top">
							<u-radio-group v-model="model.outReason" placement="row">
								<u-radio v-for="(item, index) in outReasons" :key="index" :label="item.label"
									:name="item.label">
								</u-radio>
							</u-radio-group>
						</u-form-item>
						<view class="sub-title">
							不良项
						</view>
						<view class="ng-list">
							<u-form-item v-for="(item, index) in model.ngList" :key="index" :label="item.label"
								class="label-fwn">
								<InputNumberField v-model.number="item.value" @blur="autoTotal" :min="0"
									:max="999999" />
							</u-form-item>
						</view>
						<view class="sub-title">
							生产班次
						</view>
						<u-row justify="space-between">
							<u-col span="5">
								<u-form-item label="班次" prop="shift" required class="label-fwn">
									<uni-data-select v-model="model.shift" :modelValue="model.shift" :localdata="shifts"
										format="{label}" placeholder="请选择" :clear="false"
										showSelectorPosition="top"></uni-data-select>
								</u-form-item>
							</u-col>
							<u-col span="5">
								<u-form-item label="班次时间" prop="shiftTime" required class="label-fwn">
									<DatePicker v-model="model.shiftTime" @change="shiftTimeChange" />
								</u-form-item>
							</u-col>
						</u-row>
						<u-row justify="space-between">
							<u-col span="5">
								<u-form-item label="提报方式" prop="reportingMethod" required class="label-fwn">
									<uni-data-select v-model="model.reportingMethod" :modelValue="model.reportingMethod"
										:localdata="reportingMethods" format="{label}" :clear="false"
										showSelectorPosition="top" placeholder="请选择"></uni-data-select>
								</u-form-item>
							</u-col>
							<u-col span="5">
								<!-- 原型上有，但移动端实现与接口模型上无
                                <u-form-item label="重量单位" prop="field6" required class="label-fwn">
                                <uni-data-select v-model="model.field6" :modelValue="model.field6" :localdata="list"
                                        format="{label}" placeholder="请选择"></uni-data-select> 
                                </u-form-item> -->
								<u-form-item :label="`报废${model.reportingMethod == '按重量' ? '重量' : '数量'}:`"
									prop="outNumTotal" required class="label-fwn">
									<InputNumberField v-model.number="model.outNumTotal" :disabled="true" :min="0"
										:max="999999" placeholder="自动计算">
										<template slot="suffix" v-if="model.reportingMethod==='按重量'">
											{{ workInfo.weightUnit }}
										</template>
									</InputNumberField>
								</u-form-item>
							</u-col>
						</u-row>
						<u-row justify="space-between">
							<u-col span="5">
								<u-form-item label="备注" prop="remarks" class="label-fwn">
									<InputField v-model="model.remarks" :maxlength="100" />
								</u-form-item>
							</u-col>
						</u-row>
					</u--form>
					<template slot="footer">
						<Button large @click="open1">
							历史报废记录
						</Button>
						<Button large type="primary" @click="open2" style="margin-left: 2rem;">
							提交
						</Button>
					</template>
				</FormWrap>
			</Panel>
		</Content>
		<Modal title="历史报废记录" ref="popup1" width="80%" noComfirm>
			<view class="table-demo">
				<Table ref="table" :columns="columns" requestType="post" :src="src" :params="{}" :data="params"
					pagination :tooltip="false">
					<template slot-scope="{ row,index }" slot="action">
						<view class="operationBtn" v-if="$has('deletHisBtn')" @click="deleteRow(row)">删除</view>
					</template>
				</Table>
			</view>
		</Modal>
		<Modal title="确认提交吗？" ref="popup2" @confirm="confirm2" />
		<Modal title="确认删除报废记录吗？" ref="popup3" @confirm="confirm3" />
	</Page>
</template>

<script>
	import Info from "@/components/info/index.vue";
	import Page from "@/components/page/index.vue";
	import Topbar from "@/components/topbar/index.vue";
	import Content from "@/components/content/index.vue";
	import Panel from "@/components/panel/index.vue";
	import Empty from "@/components/empty/index.vue";
	import Button from "@/components/button/index.vue";
	import FormWrap from '@/components/formWrap/index.vue';
	import InputField from '@/components/formField/inputField/index.vue';
	import InputCaptcheField from '@/components/formField/inputCaptcheField/index.vue';
	import InputNumberField from '@/components/formField/inputNumberField/index.vue';
	import NumberBoxField from '@/components/formField/numberBoxField/index.vue';
	import DatePicker from '@/components/formField/datePicker/index.vue';
	import Modal from '@/components/modal/index.vue';
	import Table from '@/components/table/index.vue';
	import fetch from "@/utils/fetch";
	import {
		getDevice
	} from "@/store/user.js";
	import filter from "@/utils/filter";
	import {
		timeIsBetweenTimeRange
	} from "@/utils/date";

	export default {
		components: {
			Page,
			Topbar,
			Content,
			Panel,
			Info,
			Empty,
			Button,
			FormWrap,
			InputField,
			InputCaptcheField,
			InputNumberField,
			NumberBoxField,
			DatePicker,
			Modal,
			Table
		},
		data() {
			return {
				workInfo: {},
				labelPosition: 'left',
				checkTypes: [{
					label: '报废',
					value: '报废',
				}, {
					label: '不良',
					value: '不良',
				}, ],
				outReasons: [],
				reportingMethods: [{
						label: '按数量',
						value: '按数量',
					},
					{
						label: '按重量',
						value: '按重量',
					}
				],
				shifts: [],
				model: {
					checkType: '报废',
					outReason: '模具原因报废',
					ngList: [], //不良项清单
					outNumTotal: '', //ngList中ngNumber和
					shift: '',
					shiftTime: Number(new Date()),
					remarks: '',
					reportingMethod: '按数量',
					workCode: '',
				},
				rules: {
					'shift': {
						type: 'string',
						required: true,
						message: '请输入',
						trigger: ['blur', 'change']
					},
					'outNumTotal': {
						type: 'number',
						required: true,
						message: '请输入',
						trigger: ['blur', 'change']
					},
				},
				src: '/dms/mobile/selectCheckSelfHistory',
				params: {},
				columns: [{
						label: '生产班次',
						value: 'shift',
					}, {
						label: '班次日期',
						value: 'shiftTime',
					}, {
						label: '提报数量',
						value: 'outNumTotal',
						type: 'number'
					}, {
						label: '类型',
						value: 'checkType',
					}, {
						label: '操作工',
						value: 'operator',
					}, {
						label: '提报时间',
						value: 'reportingTime',
						width: '30rem'
					},
					{
						label: '操作',
						slot: 'action'
					},
				],
				delId: '',
			}
		},
		methods: {
			deleteRow(row) {
				this.delId = row.id;
				this.$refs.popup3.open()
			},
			confirm3() {
				const that = this;
				fetch('delete', '/dms/workSelfCheck/delete', {
					id: this.delId
				}).then((res) => {
					that.$refs['table'] && that.$refs['table'].reload();
				});
			},
			getWorkOrderInfo(workCode) {
				fetch('get', '/dms/mobile/selfCheckScrapWorkInfo', {
					workCode
				}).then((res) => {
					this.workInfo = res;
				});
			},
			autoTotal() {
				let total = 0;
				this.model.ngList.forEach((item) => {
					total += item.value;
				});
				this.model.outNumTotal = total;
			},
			open1() {
				this.$refs.popup1.open();
				setTimeout(() => {
					this.$refs['table'] && this.$refs['table'].reload();
				}, 100);
			},
			open2() {
				this.$refs.uForm.validate().then((valid) => {
					if (valid) this.$refs.popup2.open()
				});
			},
			confirm2() {
				this.model.shiftTime = this.dayjs(this.model.shiftTime).format('YYYY-MM-DD');
				this.model.ngList = this.model.ngList.map((item) => ({
					ngNnumber: item.value,
					ngCode: item.label,
				}));
				fetch('post', '/dms/mobile/addWorkCheckSelf', null, this.model).then(() => {
					this.$toast('提交成功');
					// this.goto('/pages/workbench/inspect/index');
					uni.navigateBack()
				});
			},
			goto(url) {
				uni.navigateTo({
					url,
					animationType: "pop-in",
					animationDuration: 1000,
				})
			},
			changeCheckType() {
				this.getDictData();
			},
			getDictData() {
				fetch("get", "/dms/faultCategory/dictList", {
					name: this.model.checkType,
				}).then((res) => {
					this.outReasons = res.map((item) => ({
						label: item.value,
						value: item.value,
					}));
					this.model.outReason = this.outReasons[0].value;
				});
			},
			getPoorList() {
				this.ngList = [];
				fetch("get", "/dms/faultCategory/dictList", {
					name: "不良项",
				}).then((res) => {
					for (let i = 0; i < res.length; i++) {
						this.model.ngList.push({
							label: res[i].value,
							value: 0,
						});
					}
				});
			},
			shiftTimeChange() {
				this.model.shift = '';
				this.getShiftList();
			},
			getShiftList(status) {
				fetch("get", "/dms/mobile/getShiftList", {
					deviceNo: getDevice().deviceNo,
					shiftDate: status ? '' : this.dayjs(this.model.shiftTime).format('YYYY-MM-DD'),
				}).then((res) => {
					this.shifts = res.map((item) => ({
						label: item.shift,
						value: item.shift,
						scheduleDate: item.scheduleDate,
					}));
					if (this.shifts.length !== 0) {
						// const has = res.find(item => timeIsBetweenTimeRange(filter.formatCurrentTimeDuration(),
						//     item.shiftStartTime,
						//     item.shiftEndTime));
						// if (has)
						//     this.model.shiftId = has.id;
						// else
						//     this.model.shiftId = this.shifts[0].value;
						this.model.shift = this.shifts[0].value;
						if (status) this.$set(this.model, 'shiftTime', this.dayjs(this.shifts[0].scheduleDate)
							.valueOf());
					} else {
						this.model.shift = null;
					}
				});
			},
		},
		onLoad(params) {
			this.model.workCode = params.workCode;
			this.params.workCode = this.model.workCode;
			this.getWorkOrderInfo(params.workCode);
			this.getShiftList(true);
			this.getDictData();
			this.getPoorList();
		}
	};
</script>

<style scoped lang="scss">
	.left {
		flex: 0 auto;
		width: 50rem;
		background: #f8f8fa;
	}

	.right {
		flex: 1;
		background-color: red;
		background: #fff;
		display: flex;
		flex-direction: column;
		justify-content: space-between;
		align-items: center;
		padding: 3rem 4rem 5rem;
	}

	.ng-list {
		display: flex;
		flex-wrap: wrap;

		/deep/ .u-form-item {
			width: 45%;
			margin-left: 3%;
		}
	}

	.label-top {
		/deep/ .u-form-item__body__left {
			align-items: flex-start !important;
			margin-top: 2rem;
		}
	}

	.label-fwn {
		/deep/ .u-form-item__body__left__content__label {
			font-weight: normal !important;
		}
	}

	.sub-title {
		padding: 3rem 0;
		font-size: 2.2rem;
		font-weight: bold;
		border-bottom: 1px solid #ccc;
		margin: 2rem 0;
	}

	.table-demo {
		flex: 1;
		display: flex;
		flex-direction: column;
	}

	.operationBtn {
		color: #2979ff;
	}
</style>